package com.yuliang.vueblog.shiro;

import cn.hutool.core.bean.BeanUtil;
import com.yuliang.vueblog.entity.User;
import com.yuliang.vueblog.service.UserService;
import com.yuliang.vueblog.util.JwtUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


public class AccountRealm extends AuthorizingRealm {

    public AccountRealm() {
        System.out.println("AccountRealmh被创建了！");
    }

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("doGetAuthorizationInfo被访问！");
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("doGetAuthenticationInfo---------------");
        JwtToken jwtToken = (JwtToken) token;
        String userId = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal()).getSubject();
        System.out.println("userId"+userId);
        User user = userService.getById(Long.parseLong(userId));
        if (user == null ){
            throw  new UnknownAccountException("账户不存在！");
        }

        if (user.getStatus() == -1){
            throw new LockedAccountException("账户已被锁定！");
        }
        AccountProfile profile = new AccountProfile();

        BeanUtil.copyProperties(user,profile);

        return new SimpleAuthenticationInfo(
                profile,
                jwtToken.getCredentials(),
                getName()
        );
    }
}
